package com.mypage.view.activity.beautMore;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.async.Log;
import com.mypage.adapter.NroleAdapter;
import com.mypage.adapter.NroleAdapterRole;
import com.mypage.bean.RoleAuthority;
import com.mypage.utils.AnimViewUtils;
import com.mypage.utils.NetStateUtils;
import com.mypage.utils.SaveTemporaryData;
import com.mypage.utils.UtilsShowDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddGroupPersonActivity extends BaseActivity {

    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;
    @Bind(R.id.imgLeftBack)
    ImageView imgLeftBack;
    @Bind(R.id.textTitle)
    TextView textTitle;
    @Bind(R.id.imgRight)
    ImageView imgRight;
    @Bind(R.id.btnContent)
    Button btnContent;
    @Bind(R.id.btn_search)
    ImageView btn_search;
    @Bind(R.id.btnRole)
    Button btnRole;
    @Bind(R.id.btnQuanxian)
    Button btnQuanxian;
    @Bind(R.id.textName)
    TextView textName;
    @Bind(R.id.toastHintContents)
    TextView toastHintContent;
    @Bind(R.id.imgDeletess)
    ImageView imgDeletes;
    @Bind(R.id.topLayoutBackg)
    RelativeLayout topLayoutBackg;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private List<RoleAuthority.Levels> mListLevels;
    private List<RoleAuthority.Roles> mListRoles;
    private NroleAdapter mAdapter;
    private NroleAdapterRole mAdapterRole;
    private String mJudge;
    private UtilsShowDialog showDialog;
    private String mData;
    private String userId;
    private String userName;
    private String userRole;
    private String userQuanxian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_add_group_person);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_group_person;
    }

    public void initView() {
        topLayoutBackg.setVisibility(View.GONE);
        showDialog = new UtilsShowDialog(this);
        if ("en".equals(mEns)) {
            textTitle.setText("Add a business opportunity");
        } else {
            textTitle.setText("添加业务机会小组成员");
        }
        textName.setText(getIntent().getStringExtra("mPersionName"));
        imgRight.setImageResource(R.drawable.selector_back_left);
        getRoleOrQuan();

    }


    @OnClick({R.id.imgLeftBack, R.id.imgRight, R.id.btnContent, R.id.btn_search, R.id.btnRole, R.id.btnQuanxian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgLeftBack:
                finish();
                break;
            case R.id.imgRight:
                if (NetStateUtils.isNetworkConnected(this)) {
                    saveDataHttp();
                } else {
                    layoutTop.setVisibility(View.VISIBLE);
                    toastHintContent.setText(R.string.meg_net_no);
                    new AnimViewUtils().appearToast(topLayoutBackg);
                }


                break;
            case R.id.btn_search:
                startAct();
                break;
            case R.id.btnContent:
                startAct();
                break;
            case R.id.btnRole:
                mJudge = "role";
                showPopupWindow(btnRole);
                break;
            case R.id.btnQuanxian:
                mJudge = "quanXian";
                showPopupWindow(btnQuanxian);
                break;
        }
    }

    public void startAct() {
        Intent intent = new Intent(this, BusinCreateGroupPerson.class);
        if ("en".equals(mEns)) {
            intent.putExtra("User", "User");
        } else {
            intent.putExtra("User", "用户");
        }
        intent.putExtra("recordId", getIntent().getStringExtra("recordId"));
        layoutTop.setVisibility(View.GONE);
        topLayoutBackg.setVisibility(View.GONE);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        userName = data.getStringExtra("Name");
        btnContent.setText(data.getStringExtra("Name"));
        btnContent.setTextColor(Color.BLACK);
        userId = data.getStringExtra("mId");

        super.onActivityResult(requestCode, resultCode, data);
    }

    public void showPopupWindow(View v) {
        layoutTop.setVisibility(View.GONE);
        topLayoutBackg.setVisibility(View.GONE);
        View contentView = View.inflate(this, R.layout.popup_role, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        ListView popList = (ListView) contentView.findViewById(R.id.popList);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        setShowListView(popList, popupWindow);
        popupWindow.showAsDropDown(v);
    }

    public void setShowListView(ListView popList, PopupWindow popupWindow) {
        if ("role".equals(mJudge)) {
            mAdapterRole = new NroleAdapterRole(this, mListRoles);
            popList.setAdapter(mAdapterRole);
        } else if ("quanXian".equals(mJudge)) {
            mAdapter = new NroleAdapter(this, mListLevels);
            popList.setAdapter(mAdapter);
        }


        setPopListnener(popList, popupWindow);
    }

    public void setPopListnener(ListView popList, final PopupWindow popupWindow) {
        popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                if ("role".equals(mJudge)) {
                    btnRole.setText(mListRoles.get(position).value.toString());
                    userRole = mListRoles.get(position).value.toString();
                    btnRole.setTextColor(Color.BLACK);
                } else if ("quanXian".equals(mJudge)) {
                    btnQuanxian.setText(mListLevels.get(position).value.toString());
                    userQuanxian = mListLevels.get(position).value.toString();
                    btnQuanxian.setTextColor(Color.BLACK);
                }

            }
        });
    }

    public void getRoleOrQuan() {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "saveOpportunityTeamInit");

        Log.d("request新建业务小组角色 and 权限url ", UrlManager.getInterfaceUrl() + "?serviceName=saveOpportunityTeamInit&binding=" + RunTimeManager.getInstance().getServerBinding());
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                dispose(arg0.result.toString());
            }
        });
    }


    public void dispose(String s) {
        mListLevels = new ArrayList<>();
        mListRoles = new ArrayList<>();
        showDialog.onDismissLoadingDialog();
        RoleAuthority mCallBackData = new Gson().fromJson(s, RoleAuthority.class);
        mListLevels = mCallBackData.data.levels;
        mListRoles = mCallBackData.data.roles;

    }


    // 把数据转换成json格式。用于上传服务端
    public void createJson() {
        JSONObject object = new JSONObject();
        try {

//            object.put("id", getIntent().getStringExtra("mId"));
            object.put("opportunity", getIntent().getStringExtra("recordId"));//写死
            object.put("opportunityaccesslevel", btnQuanxian.getText().toString().trim());
            object.put("teammemberrole", btnRole.getText().toString());
            object.put("userid", userId);
            mData = "[" + object.toString() + "]";

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void saveDataHttp() {
        if (userName == null || userName == "") {
            layoutTop.setVisibility(View.VISIBLE);
            toastHintContent.setText(R.string.selector_user);
            new AnimViewUtils().appearToast(topLayoutBackg);
            return;
        } else if (userRole == null || userRole == "") {
            layoutTop.setVisibility(View.VISIBLE);
            toastHintContent.setText(R.string.selector_role);
            new AnimViewUtils().appearToast(topLayoutBackg);
            return;
        } else if (userQuanxian == null || userQuanxian == "") {
            layoutTop.setVisibility(View.VISIBLE);
            toastHintContent.setText(R.string.selector_quan);
            new AnimViewUtils().appearToast(topLayoutBackg);
            return;
        }
        createJson();
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "saveOpportunityTeam");
        params.addBodyParameter("data", mData);

        Log.d("request新建业务小组角色url ", UrlManager.getInterfaceUrl() + "?serviceName=saveOpportunityTeam&binding=" + RunTimeManager.getInstance().getServerBinding() + "&data=" + mData);
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.d("request新建业务小组角色Success:  ", arg0.result.toString());
                parseJson(arg0.result.toString());

            }
        });
    }

    public void parseJson(String str) {
        BusinChangeActivity.mToastBool = true;
        try {
            JSONObject mObj = new JSONObject(str);
            String info = mObj.getString("returnInfo");
            SaveTemporaryData.mToastStr = getString(R.string.uwxzcy) + userName + getString(R.string.saveName);
            SaveTemporaryData.mSmart = "create";
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @OnClick(R.id.imgDeletess)
    public void onClick() {
        layoutTop.setVisibility(View.GONE);
        topLayoutBackg.setVisibility(View.GONE);
    }

}
